<template>
    <div class="common-layout">
      <el-container>
        <el-page-header :icon="null" title=" " class="custom-page-header">
          <template #content>
            <div class="flex items-center">
              <el-avatar :size="32" style="margin-right: 15px;" src="img\a.jpg" />
              <span class="text-large font-600" style="margin-right: 10px;">
                <span>
                  {{ aname }}
                </span>
              </span>
              <span class="text-sm" style="margin-right: 10px; color: var(--el-text-color-regular)">
                让努力感动生命
              </span>
              <el-tag class="header-tag">冷静</el-tag>
            </div>
          </template>
          <template #extra>
            <div class="flex items-center">
              <el-button type="primary" class="ml-2 page-btn" link @click="logout">退出</el-button>
            </div>
          </template>
        </el-page-header>
  
        <!-- 先显示第二个表格 -->
        <div class="table-container">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-card>
                <el-table :data="borrowList" style="width: 100%" height="250">
                  <el-table-column fixed prop="boid" label="ID" width="70" />
                  <el-table-column prop="admin.aname" label="用户" width="100" />
                  <el-table-column prop="book.bname" label="书籍" width="100" />
                  <el-table-column prop="boout" label="借出时间" width="100" />
                  <el-table-column prop="bostill" label="归还时间" width="100" />
                  <el-table-column prop="bodeposit" label="押金" width="100" />
                  <el-table-column prop="bostate" label="借阅状态" width="100">
                    <template #default="scope">
                      <el-tag type="primary" v-if="scope.row.bostate == 1">借阅中</el-tag>
                      <el-tag type="info" v-else>已归还</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column fixed="right" label="操作" width="200">
                    <template #default="scope">
                      <el-popconfirm title="你确定要归还此书吗?" confirm-button-text="确认" cancel-button-text="取消"
                        width="200px" @confirm="returnBorrow(scope.row.boid)">
                        <template #reference>
                          <el-button size="small" type="danger">
                            <el-icon>
                              <Delete />
                            </el-icon>归还
                          </el-button>
                        </template>
                      </el-popconfirm>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>
          </el-row>
        </div>
  
        <!-- 再显示第一个表格 -->
        <div class="table-container">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-card class="book-card">
                <el-form :inline="true" class="demo-form-inline">
                  <el-form-item style="float: left;">
                    <el-input v-model="bname" placeholder="请输入要搜索的书名" @input="selectByPage(1)" />
                  </el-form-item>
                  <el-form-item style="float: right;">
                    <el-input v-model="bauthor" placeholder="请输入要搜索的姓名" @input="selectByPage(1)" />
                  </el-form-item>
                </el-form>
                <el-table v-loading="loading" :data="pageInfo.list" border style="width: 100%">
                  <el-table-column fixed prop="bid" label="书籍ID" width="100" />
                  <el-table-column fixed prop="bavatar" label="书籍图像" width="100">
                    <template #default="scope">
                      <el-avatar shape="square" :size="50" :src="'http://localhost:8080/upload/' + scope.row.bavatar" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="bname" label="书名" width="180" />
                  <el-table-column prop="bauthor" label="作者" width="100" />
                  <el-table-column prop="bpress" label="出版社" width="140" />
                  <el-table-column prop="bdate" label="出版日期" width="110" />
                  <el-table-column prop="bnumber" label="书籍数量" width="100" />
                  <el-table-column prop="classify.cid" label="分类ID" width="100" />
                  <el-table-column prop="classify.cname" label="分类" width="100" />
                  <el-table-column fixed="right" label="操作" width="200">
                    <template #default="scope">
                      <!-- 添加条件判断 -->
                      <template v-if="scope.row.bnumber > 0">
                        <el-button size="small" type="primary" @click="showUpdateBorrow(scope.row.bid)">
                          <el-icon>
                            <Edit />
                          </el-icon>借阅
                        </el-button>
                      </template>
                      <template v-else>
                        <el-button size="small" type="primary" disabled>
                          <el-icon>
                            <Edit />
                          </el-icon>借阅
                        </el-button>
                      </template>
                    </template>
                  </el-table-column>
                </el-table>
                <el-row class="row-bg" justify="center">
                  <el-pagination style="margin-top: 20px;" background layout="prev, pager, next"
                    v-model:current-page="pageInfo.pageNum" :page-count="pageInfo.pages" @update:current-page="selectByPage" />
                </el-row>
              </el-card>
            </el-col>
          </el-row>
        </div>
  
        <!-- 添加借阅表对话框开始 -->
        <el-dialog v-model="insertBorrow" title="添加用户" width="500">
          <el-form>
            <el-form-item label="用户ID" label-width="20%">
              <el-input v-model="borrowAdd.aid" autocomplete="off" />
            </el-form-item>
            <el-form-item label="借出日期" label-width="20%">
              <el-input v-model="borrowAdd.boout" autocomplete="off" />
            </el-form-item>
            <el-form-item label="归还日期" label-width="20%">
              <el-input v-model="borrowAdd.bostill" autocomplete="off" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="insertBorrowRemove">取消</el-button>
              <el-button type="primary" @click="BorrowAdd();">
                确认
              </el-button>
            </div>
          </template>
        </el-dialog>
        <!--添加借阅表的对话框结束-->
      </el-container>
    </div>
  </template>
  
  <script setup>
  import { RouterView, RouterLink } from 'vue-router';
  import router from '@/router';
  import { onMounted } from 'vue';
  import { reactive, ref, computed } from 'vue';
  import { ElLoading } from 'element-plus';
  import { ElMessage } from 'element-plus';
  import { Delete } from '@element-plus/icons-vue';
  import bookApi from '@/api/bookApi';
  import borrowApi from '@/api/borrowApi';
  import adminApi from '@/api/adminApi';
  import accountApi from '@/api/accountApi';
  import { useTokenStore } from '@/stores/token';
  
  // 用来搜索书名关键字
  const bname = ref('');
  const bauthor = ref('');
  
  //获取所有借阅记录
  const borrowList = ref([]);
  
  //定义方法获取所有借阅的信息
  function selectAllbo() {
    borrowApi.selectAll().then(resp => {
      borrowList.value = resp.data;
    });
  }
  
  //归还定义方法存储借阅表信息
  const borrowUpdate = ref({
    uid: '',
    bid: '',
    boout: '',
    bostill: '',
    bodeposit: '0',
    bostate: '0'
  });
  
  // 归还定义方法存储修改书籍信息
  const bookUpdates = ref({
    bavatar: '',
    bname: '',
    bauthor: '',
    bpress: '',
    bdate: '',
    bnumber: '',
    cid: ''
  });
  
  //存储借阅记录表
  const borrows = ref({
    boid: 0,
    aid: 0,
    bid: 0,
    boout: '',
    bostill: '',
    bodeposit: 0,
    bostate: 0
  });
  
  // 归还 在借阅中中查询所有书籍
  function returnBorrow(boid) {
    // 在这个函数内部直接调用更新函数，并传递 boid
    updateBorrowData(boid);
  };
  
  // 更新借阅数据的函数
  function updateBorrowData(boid) {
    const loading = ElLoading.service({
      lock: true,
      text: '加载中~~~',
      background: 'rgba(0, 0, 0, 0.7)',
    });
    // 根据 boid 获取借阅数据
    borrowApi.selectByBoid(boid).then(resp => {
      if (resp.data) {
        borrows.value = resp.data;
        // 更新借阅相关数据
        borrows.value.bodeposit = 0;
        borrows.value.bostate = 0;
        // 执行更新操作
        borrowApi.updateborrow(borrows.value).then(updateResp => {
          loading.close();
          if (updateResp.code === 10000) {
            // 弹出成功消息
            ElMessage({
              message: updateResp.msg,
              type: 'success',
              duration: 1200
            });
            //修改借阅表记录
            bookUpdates.value.bnumber = bookUpdates.value.bnumber + 1;
            bookApi.updateBook(bookUpdates.value);
            // 刷新表格数据
            selectAllbo();
            // 修改为新的分页函数
            selectByPage(1);
            refreshCurrentPage
          } else {
            // 弹出错误消息
            ElMessage({
              message: updateResp.msg,
              type: 'error',
              duration: 2000
            });
          }
        }).catch(error => {
          loading.close();
          console.error('更新借阅数据出错:', error);
        });
      } else {
        console.error('未获取到对应 boid 的借阅数据');
      }
    }).catch(error => {
      loading.close();
      console.error('查询借阅数据出错:', error);
    });
  }
  
  //新增借阅记录表对话框是否显示
  const insertBorrow = ref(false);
  
  // 定义方法存储修改书籍信息
  const bookUpdate = ref({
    bavatar: '',
    bname: '',
    bauthor: '',
    bpress: '',
    bdate: '',
    bnumber: '',
    cid: ''
  });
  
  //定义方法存储借阅表信息
  const borrowAdd = ref({
    uid: '',
    bid: '',
    boout: '',
    bostill: '',
    bodeposit: '100',
    bostate: '1'
  });
  
  // 点击借阅后，弹出对话框，填写借阅表
  function showUpdateBorrow(bid) {
    bookApi.selectBuBid(bid).then(resp => {
      bookUpdate.value = resp.data;
    });
    borrowAdd.value.bid = bid;
    insertBorrow.value = true;
  }
  
  // 定义方法完成借阅表的添加
  function BorrowAdd() {
    const loading = ElLoading.service({
      lock: true,
      text: '加载中~~~',
      background: 'rgba(0, 0, 0, 0.7)',
    });
    borrowApi.insert(borrowAdd.value).then(resp => {
      loading.close();
      if (resp.code === 10000) {
        // 弹出成功消息
        ElMessage({
          message: resp.msg,
          type: 'success',
          duration: 1200
        });
        //修改借阅表记录
        bookUpdate.value.bnumber = bookUpdate.value.bnumber - 1;
        bookApi.updateBook(bookUpdate.value);
        // 隐藏对话框
        insertBorrow.value = false;
        // 清空对话框中的数据
        borrowAdd.value = {
          aid: '',
          bid: '',
          boout: '',
          bostill: '',
          bodeposit: '100',
          bostate: '1'
        };
        // 刷新表格数据
        selectAllbo();
        // 修改为新的分页函数
        selectByPage(1);
      } else {
        // 弹出错误消息
        ElMessage({
          message: resp.msg,
          type: 'error',
          duration: 2000
        });
      }
    });
  }
  
  //新增借阅表对话框,点击取消按钮后清空数据
  function insertBorrowRemove() {
    insertBorrow.value = false;
    borrowAdd.value = {
      aid: '',
      bid: '',
      boout: '',
      bostill: '',
      bodeposit: '100',
      bostate: '1'
    };
  }
  
  // 表格加载开启
  const loading = ref(true);
  
  // 保存分页信息
  const pageInfo = ref({
    pages: 0,
    pageSize: 0,
    pageNum: 0
  });
  
  // 分页查询
  function selectByPage(pageNum) {
    // 表格加载关闭
    loading.value = false;
    bookApi.selectByPage(pageNum, bname.value, bauthor.value).then(resp => {
      pageInfo.value = resp.data;
    });
  }
  
  // 刷新页面
  function refreshCurrentPage() {
    const urlParams = new URLSearchParams(window.location.search);
    const currentPage = parseInt(urlParams.get('page')) || 1;
    location.reload();
  }
  
  // 默认查询第一页
  selectByPage(1);
  
  onMounted(() => {
    selectAllbo();
  });
  
  const tokenStore = useTokenStore();
  
  function logout() {
    // 重置store 中的 token
    tokenStore.$reset();
    // 跳转到登录页
    router.push('/login');
  }
  
  const aname = ref('');
  
  //获取已登录用户信息
  function getLoginInfo() {
    accountApi.getLoginInfo().then(resp => {
      aname.value = resp.data.aname;
    });
  }
  
  getLoginInfo();
  </script>
  
  <style scoped>
  .common-layout {
    display: flex;
    flex-direction: column;
    height: 100vh;
  }
  
  .el-container {
    flex: 1;
    display: flex;
    flex-direction: column;
  }
  
  .custom-page-header {
    padding: 10px 0;
    width: 100%;
    margin-bottom: 0px;
    background-color: #f0f0f0;
  }
  
  .table-container {
    display: flex;
    justify-content: center;
  }
  
  .el-card {
    width: 80%;
    margin: 0 auto;
  }
  
  .header-tag {
    background-color: #409EFF;
    color: white;
    border-radius: 5px;
  }
  
  .page-btn {
    border-radius: 5px;
  }
  
  .page-btn:hover {
    opacity: 0.8;
  }
  
  .el-menu-vertical-demo :hover {
    background-color: #555;
  }
  </style>